﻿using System;
using System.Drawing;
using System.Windows.Forms;
using ManagedWinapi;
using ManagedWinapi.Windows;

namespace wutils
{
    public class MinimizedWindowMenuItem : ToolStripMenuItem
    {
        public MinimizedWindowMenuItem(SystemWindow window)
        {
            Window = window;
            Initialize();
        }

        private SystemWindow Window { get; set; }

        private void Initialize()
        {
            Name = "item__" + Window.HWnd;
            Text = Window.Title;

            Click += ClickHandler;

            if (Window.Process.Modules.Count <= 0) return;

            Icon icon = ExtendedFileInfo.GetIconForFilename(Window.Process.Modules[0].FileName, true);
            Image = Image.FromHbitmap(icon.ToBitmap().GetHbitmap());

            WindowUtils.MinimizedWindowsChanged += OnMinimizedWindowsChanged;
        }

        private void OnMinimizedWindowsChanged(object sender, WindowEventArgs e)
        {
            if (e.Action != EventAction.REMOVED) return;
            //if(Window==null) return;
            if (Window.HWnd != e.Window.HWnd) return;
            if (GetCurrentParent() == null) return;

            GetCurrentParent().Items.Remove(this);
            Window = null;
            WindowUtils.MinimizedWindowsChanged -= OnMinimizedWindowsChanged;
            Dispose();
        }

        private void ClickHandler(object sender, EventArgs e)
        {
            Restore();
        }

        public void Restore()
        {
            WindowUtils.Restore(Window);
        }
    }
}